import React, { useEffect, useState } from "react";
import Select from "../../../Select";
import { isPromise } from "@ct0/functions";
import type { FieldBaseType } from "../../type";
import type { SelectOptions } from "../../../Select/type";

export default function SelectField({
  field,
  isValid,
  onChange,
}: {
  field: FieldBaseType<Array<string | number>>;
  isValid: boolean;
  onChange: (v: Array<string | number>) => void;
}) {
  const { value, defaultValue, disabled, placeholder, options, meta } = field;
  const search = meta?.search ? true : false;

  const [opts, setOpts] = useState<SelectOptions>([]);
  useEffect(() => updateOpts(), [options]);

  const updateOpts = (text?: string) => {
    if (typeof options == "undefined") return;
    else if (typeof options == "function") {
      const opt = options(text);
      if (isPromise(opt)) opt.then((r) => setOpts(r));
      else setOpts(opt as any);
    } else {
      if (text) {
        const opts = options.filter(
          (i) => i.label.includes(text) || String(i.value).includes(text)
        );
        setOpts(opts);
      } else setOpts(options);
    }
  };

  return (
    <Select
      placeholder={placeholder}
      disabled={disabled}
      invalid={!isValid}
      value={value ?? defaultValue}
      multiple
      options={opts}
      search={search}
      onInputChange={updateOpts}
      onChange={onChange}
      disabledValueOptions={meta?.disabledValueOptions}
      notFoundContent={meta?.notFoundContent}
    />
  );
}
